/**
 * Ant Design Pro v4 use `@ant-design/pro-layout` to handle Layout.
 * You can view component api by:
 * https://github.com/ant-design/ant-design-pro-layout
 */
import ProLayout, { SettingDrawer, getPageTitle } from '@ant-design/pro-layout';
import React, { useEffect, useState } from 'react';
import { Link, useIntl, connect, history } from 'umi';
import { SyncOutlined, CheckOutlined } from '@ant-design/icons';
import { Modal, Button, Tag, List, Spin, Empty } from 'antd';
import RightContent from '@/components/GlobalHeader/RightContent';
import { ELDefaultFooter } from '@/components/PageFooter'
import logo from '../asserts/favicon.png';
import styles from './style.less'
import PageLoading from '@/components/PageLoading'
import TextButton from '@/components/TextButton'



const BasicLayout = (props) => {
  const {
    dispatch,
    children,
    settings,
    menuData,
    collapsed,
    location = {
      pathname: '/',
    },
    currentEnterprise = {},
    userEnterpriseList = []
  } = props;

  const [isChangeEnterpriseModalVisible, setChangeEnterpriseModalVisible] = useState(false);
  const [autoCollapseTask, setAutoCollapseTask] = useState();
  const { formatMessage } = useIntl();

  useEffect(() => {
    if (dispatch) {
      dispatch({
        type: 'user/getMyInfo',
      });
      dispatch({
        type: 'enterprise/getUserCurrentEnterprise',
      }).then(() => {
        dispatch({
          type: 'permission/queryMyPermission',
          payload: props.route.routes
        });
      })
    }

    return () => {
      if (autoCollapseTask) {
        clearTimeout(autoCollapseTask)
      }
    }
  }, []);

  useEffect(() => {
    if (!collapsed) {
      autoCloseAutoCollapse()
    }
  }, [collapsed])


  useEffect(() => {
    if (currentEnterprise.enterpriseId === 0) {
      history.replace('/home/center')
    }
  }, [currentEnterprise])

  const autoCloseAutoCollapse = () => {
    if (autoCollapseTask) {
      clearTimeout(autoCollapseTask)
    }
    let autoCollapse = setTimeout(() => {
      console.log('隐藏菜单')
      handleMenuCollapse(true)
    }, 10 * 1000)
    setAutoCollapseTask(autoCollapse)
  }

  const handleMenuCollapse = (payload) => {
    if (dispatch) {
      dispatch({
        type: 'global/changeLayoutCollapsed',
        payload,
      });
    }
  }; // get children authority

  const onPageChange = () => {
    autoCloseAutoCollapse()
  }

  const showUserEnterprise = (event) => {
    if (dispatch) {
      dispatch({
        type: 'enterprise/listUserEnterprise',
      });
    }
    setChangeEnterpriseModalVisible(true)
    event.preventDefault();
    event.stopPropagation();
  }


  const titleRender = (
    <>
      <div className={styles.entepriseTitle} onClick={showUserEnterprise}>{currentEnterprise.enterprise && currentEnterprise.enterprise.name} <SyncOutlined className={styles.changeEnterprise} /></div>
      <div className={styles.excellentPmSupport}>UL suuprt</div>
    </>
  )



  const pageTitleRender = (props, defaultPageTitle, info) => {
    let excellentpmName = useIntl().formatMessage({
      id: 'excellentpm.name',
    })
    // 定义浏览器tab标题
    if (typeof info.pageName === "string") {
      return excellentpmName + '-' + info.pageName
    }
    // console.log(props, defaultPageTitle, info)
    document.title = excellentpmName
    return excellentpmName;
  }

  if (!menuData || menuData.length === 0) {
    return <PageLoading></PageLoading>
  }

  return (
    <>
      <ProLayout
        className={styles.proLayout}
        logo={logo}
        title={titleRender}
        pageTitleRender={pageTitleRender}
        formatMessage={formatMessage}
        onCollapse={handleMenuCollapse}
        onMenuHeaderClick={() => history.push('/')}
        menuItemRender={(menuItemProps, defaultDom) => {
          if (menuItemProps.isUrl || !menuItemProps.path) {
            return defaultDom;
          }
          return <Link to={menuItemProps.path}>{defaultDom}</Link>;
        }}
        subMenuItemRender={(menuItemProps, defaultDom) => {
          // console.log(menuItemProps, defaultDom)
          return <div onClick={onPageChange}>{defaultDom}</div>
        }}
        breadcrumbRender={() => []}
        footerRender={() => <ELDefaultFooter />}
        onPageChange={onPageChange}
        menuDataRender={() => menuData}
        rightContentRender={() => <RightContent />}
        {...props}
        {...settings}
      >
        {children}
      </ProLayout>
      {/* <SettingDrawer
        settings={settings}
        onSettingChange={(config) =>
          dispatch({
            type: 'settings/changeSetting',
            payload: config,
          })
        }
      /> */}
      <Modal title="我的企业"
        visible={isChangeEnterpriseModalVisible}
        onCancel={() => {
          setChangeEnterpriseModalVisible(false)
        }}
        footer={null}>
        <List
          dataSource={userEnterpriseList}
          renderItem={
            enterprise => (
              <List.Item
                className={styles.enterpriseItem}
                extra={<div className={styles.operate}>
                  {enterprise.isCurrent === 1 ? (<Button size="small" shape="round" type="primary"><CheckOutlined className={styles.checkoutClass} /></Button>) :
                    (<TextButton onClick={() => {
                      if (dispatch) {
                        dispatch({
                          type: 'enterprise/setCurrentEnterprse',
                          payload: enterprise
                        }).then((success) => {
                          if (success) {
                            history.go(0);
                          }
                        });
                      }
                    }} size="small" shape="round" type="primary">设置为当前</TextButton>)}
                </div>}
              >
                <List.Item.Meta
                  title={<div className={styles.enterpriseName}>{enterprise.enterprise.name}</div>}
                />
                <Tag color="#108ee9" >{enterprise.enterpriseRoleName}</Tag>
              </List.Item>
            )
          }
        >
        </List>
      </Modal>
    </>
  );
};



const mapStateToProps = ({ global, settings, permission, enterprise }) => {
  return {
    currentEnterprise: enterprise.currentEnterprise,
    userEnterpriseList: enterprise.userEnterpriseList,
    myInfo: global.myInfo,
    collapsed: global.collapsed,
    settings,
    menuData: permission.menuData,
  }
}

export default connect(mapStateToProps)(BasicLayout);
